package com.f.clickhouse;

import com.clickhouse.client.ClickHouseClient;
import com.clickhouse.client.ClickHouseCredentials;
import com.clickhouse.client.ClickHouseNodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * clickhouse 配置
 *
 * @author liuf
 * @date 2023/6/15 15:21
 */
@Configuration
@EnableConfigurationProperties(ClickHouseProperties.class)
public class ClickHouseConfig {

    @Autowired
    private ClickHouseProperties clickHouseProperties;

    @Bean
    public ClickHouseNodes clickHouseNodes() {
        return ClickHouseNodes.of(clickHouseProperties.getUrl());
    }

    @Bean
    @ConditionalOnMissingBean
    public FieldToColumn fieldToColumn() {
        return FieldToColumn.DEFAULT;
    }

    @Bean
    @ConditionalOnMissingBean
    public ClickHouseClient clickHouseClient() {
        final ClickHouseCredentials credentials = ClickHouseCredentials.fromUserAndPassword(clickHouseProperties.getUsername(), clickHouseProperties.getPassword());
        return ClickHouseClient.builder()
                .defaultCredentials(credentials).build();
    }

    @Bean(destroyMethod = "destroy")
    public ClickHouseTemplate clickHouseTemplate(ClickHouseClient clickHouseClient, ClickHouseNodes clickHouseNodes, FieldToColumn fieldToColumn) {
        return new ClickHouseTemplate(clickHouseClient, clickHouseNodes, fieldToColumn);
    }

}
